package com.leyou.auth.service.impl;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.service.UserAuthService;
import com.leyou.common.constants.RedisConstants;
import com.leyou.common.constants.UserTokenConstants;
import com.leyou.common.entity.Payload;
import com.leyou.common.entity.UserInfo;
import com.leyou.common.exceptios.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.common.utils.JwtUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.security.SignatureException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author 虎哥
 */
@Service
public class UserAuthServiceImpl implements UserAuthService {

    private final UserClient userClient;
    private final JwtProperties prop;
    private final StringRedisTemplate redisTemplate;

    public UserAuthServiceImpl(UserClient userClient, JwtProperties prop, StringRedisTemplate redisTemplate) {
        this.userClient = userClient;
        this.prop = prop;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void login(String username, String password, HttpServletResponse response) {
        // 1.授权中心携带用户名密码，到用户中心查询用户
        UserDTO user = null;
        try {
            user = userClient.queryUserByUsernameAndPassword(username, password);
        } catch (FeignException e) {
            // 把调用远程查询执行异常信息，返回到前端
            throw new LyException(e.status(), e.contentUTF8());
        }

        // 2.查询如果正确，生成JWT凭证
        // 2.1.生成jti
        String jti = JwtUtils.createJTI();
        // 2.2.生成token
        String token = JwtUtils.generateTokenWithJTI(
                new UserInfo(user.getId(), user.getUsername()), jti, prop.getPrivateKey());

        // 3.把token的id（JTI）写入redis，以用户id为key，以jti为值，设置有效期
        redisTemplate.opsForValue().set(RedisConstants.JTI_KEY_PREFIX + user.getId(), jti,
                RedisConstants.TOKEN_EXPIRE_MINUTES, TimeUnit.MINUTES);

        // 4.把JWT写入用户cookie
        writeTokenInCookie(response, token);
    }

    @Override
    public String verify(HttpServletRequest request) {
        // 1.服务端接收请求，获取cookie
        String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
        if (StringUtils.isBlank(token)) {
            throw new LyException(400, "未登录或者登录已经过期");
        }
        // 2.验证cookie中的token，并获取其中的信息
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        } catch (SignatureException | ExpiredJwtException e) {
            // 无效的token，返回400
            throw new LyException(400, "未登录或者登录已经过期");
        }
        // 3.验证jti
        // 3.1.获取用户信息
        UserInfo userInfo = payload.getUserInfo();
        // 3.2.获取redis中的JTI
        String cacheJTI = redisTemplate.opsForValue().get(RedisConstants.JTI_KEY_PREFIX + userInfo.getId());
        // 3.3.比较当前token的jti和redis中的JTI
        if(!StringUtils.equals(cacheJTI, payload.getId())){
            // 无效的token，返回400
            throw new LyException(400, "未登录或者登录已经过期");
        }
        // 4.返回用户名
        return userInfo.getUsername();
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        // 1.服务端接收请求，获取cookie
        String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
        if (StringUtils.isBlank(token)) {
            // 未登录，什么都不做
            return;
        }
        // 2.验证cookie中的token，并获取其中的信息
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        } catch (SignatureException | ExpiredJwtException e) {
            // 无效的token，什么都不做
            return;
        }
        // 3.删除redis中的JTI
        UserInfo user = payload.getUserInfo();
        redisTemplate.delete(RedisConstants.JTI_KEY_PREFIX + user.getId());

        // 4.删除cookie
        CookieUtils.deleteCookie(UserTokenConstants.COOKIE_NAME, UserTokenConstants.DOMAIN, response);
    }

    private void writeTokenInCookie(HttpServletResponse response, String token) {
    /*
    Cookie cookie = new Cookie(UserTokenConstants.COOKIE_NAME, token);
    cookie.setPath("/"); // cookie作用的请求路径，/ 代表一切路径
    cookie.setMaxAge(-1); // 有效期，到期自动删除， -1代表浏览器关闭自动删除
    cookie.setHttpOnly(true);// true：禁止JS代码操作cookie。避免XSS攻击
    cookie.setDomain(UserTokenConstants.DOMAIN);// cookie作用的域名
    response.addCookie(cookie);
    */
        CookieUtils.builder(response)
                .domain(UserTokenConstants.DOMAIN)
                .httpOnly(true)
                .build(UserTokenConstants.COOKIE_NAME, token);
    }
}
